using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace FluentSilverlight.Expressions.TextItems
{
    public class WatermarkEvaluator
    {
        private readonly TextBox textBox;
        private readonly string watermark;

        public WatermarkEvaluator(TextBox textBox, string watermark)
        {
            this.textBox = textBox;
            this.watermark = watermark;

            textBox.Loaded += (s, e) => Evaluate();
            textBox.LostFocus += (s, e) => Evaluate();
            textBox.GotFocus += (s, e) => RemoveWatermark();
        }

        public void Evaluate()
        {
            if (IsInWatermarkMode && textBox.Text == watermark)
                return;

            if (string.IsNullOrEmpty(textBox.Text))
                ApplyWatermark();
            else
                RemoveWatermark();
        }

        public bool IsInWatermarkMode
        {
            get { return WaterMarkOnDependencyObject.GetWaterMarkOn(textBox); }
        }

        private void RemoveWatermark()
        {
            var watermarkIsOn = WaterMarkOnDependencyObject.GetWaterMarkOn(textBox);
            if (!watermarkIsOn) return;

            if (textBox.Text == watermark)
                textBox.Text = "";

            textBox.Foreground = new SolidColorBrush(Colors.Black) { Opacity = 1 };
            textBox.FontStyle = FontStyles.Normal;

            WaterMarkOnDependencyObject.SetWaterMarkOn(textBox, false);
        }

        private void ApplyWatermark()
        {
            WaterMarkOnDependencyObject.SetWaterMarkOn(textBox, true);
            textBox.Text = watermark;

            textBox.Foreground = new SolidColorBrush(Color.FromArgb(100, 0, 0, 0)); ;
            textBox.FontStyle = FontStyles.Italic;
        }
    }
}